<?php  

if(!class_exists("ServiceFactory"))
    die("Không tìm thấy class ServiceFactory!");

class ImageResize
{
    public static function resize($imagepath, $new_width = "0", $new_height = "0")
    {
        $image = ImageResize::open($imagepath);
        
        if ($image == false) 
        {
            return false;
        }
        
        $width = imagesx($image);
        $height = imagesy($image);
        $new_width = floatval($new_width);
        $new_height = floatval($new_height); 
        
        if ($new_width > 0 && $new_height <= 0) {
            $new_height = $height * ($new_width/$width);
        } elseif ($new_height > 0 && $new_width <= 0) {
            $new_width = $width * ($new_height/$height);
        } elseif(!$new_height <= 0 && $new_width <= 0) {
            return $image;
        }    
        
        $image_resized = imagecreatetruecolor($new_width, $new_height);
        imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        
        return $image_resized;
    } 
    
    public static function open ($file) 
    {
        # JPEG:
        $im = @imagecreatefromjpeg($file);
        if ($im !== false) { return $im; }
        # GIF:
        $im = @imagecreatefromgif($file);
        if ($im !== false) { return $im; }
        # PNG:
        $im = @imagecreatefrompng($file);
        if ($im !== false) { return $im; }
        # Try and load from string:
        $im = @imagecreatefromstring(file_get_contents($file));
        if ($im !== false) { return $im; }
        return false;
    } 
    
}

class JsonServices
{
    public static function message($succ, $message){
        echo '{"message":"'.$message.'"}';
    }
    
    public static function error($message, $errorCode=0){
        echo '{"success":"false", "message":"'.$message.'","errorCode":"'.$errorCode.'"}';
    }
    
    public static function success($message, $items=false){
        if(!$items)
            echo '{"success":"true", "message":"'.$message.'"}';
        else
            echo '{"success":"true", "message":"'.$message.'","items":'. $items .'}';
    }
    
    public static function write($message){
        echo $message;
    }
}

class Response
{
    public static function addQueryArg() {
        $ret = '';
        if ( is_array( func_get_arg(0) ) ) {
            if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
                $uri = $_SERVER['REQUEST_URI'];
            else
                $uri = @func_get_arg( 1 );
        } else {
            if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
                $uri = $_SERVER['REQUEST_URI'];
            else
                $uri = @func_get_arg( 2 );
        }
        
        if ( $frag = strstr( $uri, '#' ) )
            $uri = substr( $uri, 0, -strlen( $frag ) );
        else
            $frag = '';
        
        if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
            $protocol = $matches[0];
            $uri = substr( $uri, strlen( $protocol ) );
        } else {
            $protocol = '';
        }
        
        if ( strpos( $uri, '?' ) !== false ) {
            $parts = explode( '?', $uri, 2 );
            if ( 1 == count( $parts ) ) {
                $base = '?';
                $query = $parts[0];
            } else {
                $base = $parts[0] . '?';
                $query = $parts[1];
            }
        } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
            $base = $uri . '?';
            $query = '';
        } else {
            $base = '';
            $query = $uri;
        }
        
       	parse_str( $query, $qs );
        if ( get_magic_quotes_gpc() )
            $qs = array_map('stripslashes', $qs );
        
        $qs = array_map('urlencode', $qs);
        
        if ( is_array( func_get_arg( 0 ) ) ) {
            $kayvees = func_get_arg( 0 );
            $qs = array_merge( $qs, $kayvees );
        } else {
            $qs[func_get_arg( 0 )] = func_get_arg( 1 );
        }
        
        foreach ( $qs as $k => $v ) {
            if ( $v === false )
                unset( $qs[$k] );
        }
        
        $ret = Response::httpBuildQuery( $qs, NULL, '&', '', false );
        $ret = trim( $ret, '?' );
        $ret = preg_replace( '#=(&|$)#', '$1', $ret );
        $ret = $protocol . $base . $ret . $frag;
        $ret = rtrim( $ret, '?' );
        
        return $ret;
    }
    
    // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
    public static function httpBuildQuery($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
        $ret = array();
        foreach ( (array) $data as $k => $v ) {
            if ( $urlencode)
                $k = urlencode($k);
            if ( is_int($k) && $prefix != null )
                $k = $prefix.$k;
            if ( !empty($key) )
                $k = $key . '%5B' . $k . '%5D';
            if ( $v === NULL )
                continue;
            elseif ( $v === FALSE )
                $v = '0';
            
            if ( is_array($v) || is_object($v) )
                array_push($ret,Response::httpBuildQuery($v, '', $sep, $k, $urlencode));
            elseif ( $urlencode )
                array_push($ret, $k.'='.urlencode($v));
            else
                array_push($ret, $k.'='.$v);
        }
        
        if ( NULL === $sep )
            $sep = ini_get('arg_separator.output');
        
        return implode($sep, $ret);
    }

    public static function redirect($url)
    {
        header("location: $url");
        exit();
    }
    
    public static function json($json)
    {
        echo $json;
    }
    
    public static function toJson($arrayObj)
    {
        $r = array();
        foreach ($arrayObj as $i)
        {
            $r[] = $i->toArray();
        }
        return json_encode($r);
    }
    
    public static function message($succ, $message){
        JsonServices::message($succ, $message);
    }
    
    public static function error($message, $errorCode=0){
        JsonServices::error($message, $errorCode);
        exit();
    }
    
    public static function success($message,$items=false){
        JsonServices::success($message,$items);
    }
    
    public static function write($message){
        JsonServices::write($message);
    }
}

class TextUtility
{
    public static function Normalize($text)
    {
        return strip_tags($text, "<a><strong><em>");
    }
    
    public static function htmlEncode($text)
    {
        return htmlspecialchars($text, ENT_QUOTES);
    }
    
    public static function htmlDecode($text)
    {
        return htmlspecialchars_decode($text);
    }
    
    public static function bbCodeFormat($str)
    {
        $simple_search = array(
                    '/\[b\](.*?)\[\/b\]/is',
                    '/\[i\](.*?)\[\/i\]/is',
                    '/\[u\](.*?)\[\/u\]/is',
                    '/\[url\=(.*?)\](.*?)\[\/url\]/is',
                    '/\[url\](.*?)\[\/url\]/is',
                    '/\[mail\=(.*?)\](.*?)\[\/mail\]/is',
                    '/\[mail\](.*?)\[\/mail\]/is',
                    '/\[font\=(.*?)\](.*?)\[\/font\]/is',
                    '/\[size\=(.*?)\](.*?)\[\/size\]/is',
                    '/\[color\=(.*?)\](.*?)\[\/color\]/is'
                    );
        
        $simple_replace = array(
                    "<strong>$1</strong>",
                    "<em>$1</em>",
                    "<u>$1</u>",
                    "<a href='$1'>$2</a>",
                    "<a href='$1'>$1</a>",
                    "<a href='mailto:$1'>$2</a>",
                    "<a href='mailto:$1'>$1</a>",
                    "<span style='font-family: \"$1\";'>$2</span>",
                    "<span style='font-size: $1em;'>$2</span>",
                    "<span style='color: $1;'>$2</span>"
                    );
        
        $str = preg_replace ($simple_search, $simple_replace, $str);
        return $str;
    }
    
}

class DateUtility
{

    public static function friendlyDate($str, $format="d/m/Y")
    {
        return date($format, strtotime($str));
    }
    
    public static function now()
    {
        return date("Y/m/d H:i:s A");
    }
}

class InfoArea
{
    public static function showInfo($message, $title="Thông tin", $type="")
    {
        echo "<div class=InfoArea><div class='InfoItem {$type}'><h4>$title</h4><p>$message</p></div></div>";
    }
}

class RedirectMessage
{
    public static function info($message, $type="", $title="")
    {
        $_SESSION['info'] = 'true';
        $_SESSION['message'] = $message;
        $_SESSION['type'] = $type;
        $_SESSION['title'] = "Thông tin";
        
        if(!empty($type))
        {
            if(empty($title))
            {
                if ($type == "Error")
                {
                    $title = "Có lỗi xảy ra!";
                }
                elseif($type == "Warning")
                {
                    $title = "Cảnh báo!";
                }
                else 
                    $title = "Thông tin";
            }
            $_SESSION['title'] = $title;
        }
    }
    
    public static function hasMessage()
    {
        return isset($_SESSION['info']) && !empty($_SESSION['info']) && $_SESSION['info'] == 'true';
    }
    
    public static function getMessage($key = "message")
    {
        if(isset($_SESSION[$key]))
            return $_SESSION[$key];
        
        return "";
    }
    
    public static function removeMessage()
    {
        if(RedirectMessage::hasMessage())
        {
            unset($_SESSION['info']);
            unset($_SESSION['message']);
            unset($_SESSION['title']);
            unset($_SESSION['type']);
            return true;
        }
        return false;
    }
    
}

class Session
{
    public static function start($timeout = 1800, $name = "nowchat")
    {
        session_set_cookie_params($timeout, "/");
        session_name($name);
        session_start();
    }
}

class nowchat
{

    public static function systemSetting($setingName = '', $title = "System setting", $comment = "", $size = 20)
    {
        if(!empty($setingName))
        {
            $sys = ServiceFactory::get("SystemConfiguration");
            echo "<label for='$setingName'>$title</label>";
            echo "<input type='text' name='$setingName' id='$setingName' size='$size' value='{$sys->getSetting($setingName)}'/>";
            echo "<small>$comment</small>";
        }
    }
    
    public static function roleDropdownList($name, $nochoice = "", $selected = 0)
    {
        echo "<select name='$name'>";
        if(!empty($nochoice))
            echo "<option value=''>$nochoice</option>";
        
        $roles = ServiceFactory::get("CommonService")->getAllRoles();
        foreach ($roles as $role)
        {
            echo "<option value='{$role->getRoleName()}'>{$role->getRoleName()}</option>";
        }
        echo "</select>";
    }
    
    public static function checkboxSystemSetting($setingName, $title = "", $comment = "")
    {
        $ck = (ServiceFactory::get("SystemConfiguration")->getSetting($setingName) == "1")?" checked='checked' ":"";
        
        echo "<label class='Normal' for='$setingName'>";
        echo "<input type='checkbox' name='$setingName' id='$setingName' $ck/>";
        echo $title;
        echo "</label>";
        echo "<small>$comment</small>";
    }
    
    public static function userProperty($user, $property, $title = "", $comment = "", $size = 30, $length = 100, $dis = false)
    {
        if(!$user)
            return;
        
        $propertyValue = $user->getProperty($property);
        
        if($dis)
            $dis = "disabled='disabled'";
        
        echo "<label for='$property'>$title</label>";
        echo "<input type='text' name='$property' id='$property' size='$size' maxlength='$length' value='$propertyValue' $dis />";
        echo "<small>$comment</small>";
    }
    
    public static function userOption($user, $optionName, $title = "", $comment = "")
    {
        if(!$user)
            return;
        
        $ck = (ServiceFactory::get("UserService")->getUserOption($user->getID(), $optionName) == "1")?" checked='checked' ":"";
        
        echo "<label class='Normal' for='$optionName'>";
        echo "<input type='checkbox' name='$optionName' id='$optionName' $ck/>";
        echo $title;
        echo "</label>";
        echo "<small>$comment</small>";
    }
    
    public static function birthdaySelector($user, $id, $title = "")
    {
        echo "<label>$title</label>";
        echo "<div class='Birthday'>";
        echo "<select id='$id-month' name='$id-month'>";
        
        $birthday = getdate(strtotime($user->getBirthday()));
        for($i = 1; $i <= 12; $i++)
        {
            if($i == intval($birthday['mon']))
                echo "<option value='$i' selected='selected'>Tháng $i</option>";
            else
                echo "<option value='$i'>Tháng $i</option>";
        }
        
        $day = $birthday['mday'];
        $year = $birthday['year'];
        
        echo "</select>";
        echo "<label for='$id-day'>Ngày</label>";
        echo "<input name='$id-day' id='$id-day' value='$day' size='2' maxlength='2' type='text' />";
        echo "<label for='$id-year'>Năm</label>";
        echo "<input name='$id-year' id='$id-year' value='$year' size='4' maxlength='4' type='text' />";
        echo "</div>";
    }
    
    public static function listAvatar($id = "", $usetype = "checkbox", $avid = 0, $start = 0, $all = false, $userAvatar = false)
    {
        $commonService = ServiceFactory::get("CommonService");
        $avatarList = $commonService->getDefaultAvatars($start, $all);
        
        if($userAvatar)
        {
            $userUpload = $commonService->getAllAvatarsUploadedByUser($userAvatar, $start, $all);
            if(count($userUpload))
            {
                foreach($userUpload as $usu)
                {
                    $avatarList[] = $usu;
                }
            }
        }
        
        if(count($avatarList))
        {
            echo "<ul class='AvatarList' id='$id'>";
            
            for($i = 0 ; $i < count($avatarList); $i++)
            {
                $title = "Avatar";
                
                $src = $commonService->getAvatarSrc($avatarList[$i]->getID(), 2);
                $inuse = $commonService->canDeleteAvatar($avatarList[$i]->getID());
                if(!$inuse && $usetype == 'checkbox')
                {
                    $inuse = "disabled='disabled'";
                    $title = "Avatar này đang được sử dụng";
                }
                else
                    $inuse = "";
                
                $ck = "";
                if($avid == $avatarList[$i]->getID())
                    $ck = "checked='checked'";
                
                echo "<li>";
                if(!empty($usetype))
                    echo "<input $inuse type='$usetype'  value='{$avatarList[$i]->getID()}' name='{$id}[]' id='$id-$i' $ck />";
                echo "<img id='avatar' src='$src' title='$title' alt='avatar' /></li>";
            }
            echo "<div style='clear:both;'></div>";
            echo "</ul>";
            echo "<div style='clear:both;'></div>";
        }
    }
    
    public static function listEmoticon($id = "", $usetype = "checkbox", $emName = "")
    {
        $commonService = ServiceFactory::get("CommonService");
        $sys = ServiceFactory::get("SystemConfiguration");
        
        $emotes = $commonService -> getAllEmotesTheme();
        
        if(count($emotes))
        {
            echo "<ul class='EmoticonList' id='$id'>";
            foreach($emotes as $key => $value)
            {
                $src = $sys->getSetting("site-url") . "/" . $sys->getSetting("emoticon-path") . "/" . $key . "/" . $value['Icon'];
                
                echo "<li>";
                $ck = "";
                
                if($emName == $key)
                    $ck = "checked='checked'";
                
                if(!empty($usetype))
                    echo "<input type='$usetype' name='{$id}[]' id='$id-$i' value='$key' $ck />";
                
                echo "<img src='$src' /><div class='Emotes'><div>Name: {$value['Name']}</div><div>Author: {$value['Author']}</div></div></li>";
            }
            
            echo "<div style='clear:both'></div></ul><div style='clear:both'></div>";
        }
    }
    
    public static function uploadFile($id, $title = "", $comment = "", $size = 30)
    {
        $dis = "";
        if(ServiceFactory::get("SystemConfiguration")->getSetting("user-can-upload-avatar") != "1")
            $dis = "disabled='disabled'";
        
        echo "<label for='$id'>$title</label>";
        echo "<input $dis type='file' name='$id' id='$id' size='$size' />";
        echo "<small>$comment</small>";
        
        if(!empty($dis))
            echo "<small class='Disabled'>Bạn không thể upload avatar</small>";
    }
}
?>